#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
HTML整合工具
功能：读取CSV文件中的HTML信息，整合生成索引页面
"""

import argparse
import pandas as pd
import os
import shutil
from pathlib import Path
from datetime import datetime

class HTMLIntegrator:
    def __init__(self, source_file, output_dir, page_name, server_ip, server_port):
        self.source_file = source_file
        self.output_dir = Path(output_dir)
        self.page_name = page_name
        self.server_ip = server_ip
        self.server_port = server_port
        
        # 创建带时间戳的子文件夹
        self.timestamp = datetime.now().strftime('%Y%m%d%H%M%S')
        self.timestamped_dir = self.output_dir / self.timestamp
        self.html_subdir = self.timestamped_dir / "pages"
        
    def load_data(self):
        """加载CSV数据"""
        try:
            self.data = pd.read_csv(self.source_file)
            required_columns = ['Title', 'Content', 'Path']
            
            if not all(col in self.data.columns for col in required_columns):
                raise ValueError(f"CSV文件必须包含以下列: {required_columns}")
                
            print(f"成功加载数据: {len(self.data)} 行")
            return True
        except Exception as e:
            print(f"加载数据失败: {e}")
            return False
    
    def setup_directories(self):
        """创建输出目录结构"""
        try:
            self.timestamped_dir.mkdir(parents=True, exist_ok=True)
            self.html_subdir.mkdir(parents=True, exist_ok=True)
            print(f"创建时间戳目录: {self.timestamped_dir}")
            print(f"创建HTML子目录: {self.html_subdir}")
            return True
        except Exception as e:
            print(f"创建目录失败: {e}")
            return False
    
    def copy_html_files(self):
        """复制HTML文件到子目录"""
        copied_files = []
        
        for index, row in self.data.iterrows():
            source_path = Path(row['Path'])
            
            if not source_path.exists():
                print(f"警告: 文件不存在 {source_path}")
                continue
                
            # 生成目标文件名
            target_filename = f"{index:03d}_{source_path.stem}.html"
            target_path = self.html_subdir / target_filename
            
            try:
                shutil.copy2(source_path, target_path)
                copied_files.append({
                    'index': index,
                    'title': row['Title'],
                    'content': row['Content'] if pd.notna(row['Content']) else '',
                    'original_path': str(source_path),
                    'target_filename': target_filename
                })
                print(f"复制文件: {source_path} -> {target_filename}")
            except Exception as e:
                print(f"复制文件失败 {source_path}: {e}")
        
        return copied_files
    
    def generate_index_html(self, copied_files):
        """生成主索引HTML文件"""
        html_content = f"""
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{self.page_name}</title>
    <style>
        body {{
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }}
        .header {{
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            border-radius: 10px;
            text-align: center;
            margin-bottom: 30px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }}
        .header h1 {{
            margin: 0;
            font-size: 2.5em;
        }}
        .stats {{
            background: white;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 30px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }}
        .file-list {{
            background: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }}
        .file-item {{
            border-bottom: 1px solid #eee;
            padding: 20px;
            transition: background-color 0.3s;
        }}
        .file-item:hover {{
            background-color: #f8f9fa;
        }}
        .file-item:last-child {{
            border-bottom: none;
        }}
        .file-title {{
            font-size: 1.3em;
            font-weight: bold;
            color: #333;
            margin-bottom: 8px;
        }}
        .file-title a {{
            color: #667eea;
            text-decoration: none;
        }}
        .file-title a:hover {{
            text-decoration: underline;
        }}
        .file-content {{
            color: #666;
            margin-bottom: 10px;
            line-height: 1.5;
        }}
        .file-meta {{
            font-size: 0.9em;
            color: #999;
        }}
        .index-number {{
            display: inline-block;
            background: #667eea;
            color: white;
            width: 30px;
            height: 30px;
            border-radius: 50%;
            text-align: center;
            line-height: 30px;
            margin-right: 15px;
            font-weight: bold;
        }}

    </style>
</head>
<body>
    <div class="header">
        <h1>{self.page_name}</h1>
        <p>{self.page_name}</p>
    </div>
    
    <div class="stats">
        <h3>📊 报告概览</h3>
        <p>报告项目数: <strong>{len(copied_files)}</strong></p>
        <p>生成时间: <strong>{pd.Timestamp.now().strftime('%Y-%m-%d %H:%M:%S')}</strong></p>
    </div>
    
    <div class="file-list">
"""
        
        for file_info in copied_files:
            html_content += f"""
        <div class="file-item">
            <div class="file-title">
                <span class="index-number">{file_info['index'] + 1}</span>
                <a href="pages/{file_info['target_filename']}" target="_blank">{file_info['title']}</a>
            </div>
"""
            if file_info['content']:
                html_content += f"""
            <div class="file-content">{file_info['content']}</div>
"""
            
            html_content += """
        </div>
"""
        
        html_content += """
    </div>
</body>
</html>
"""
        
        # 保存主HTML文件
        main_html_path = self.timestamped_dir / f"{self.page_name}.html"
        with open(main_html_path, 'w', encoding='utf-8') as f:
            f.write(html_content)
        
        print(f"生成主HTML文件: {main_html_path}")
        return main_html_path
    
    def integrate(self):
        """执行整合流程"""
        print("开始HTML整合流程...")
        
        # 1. 加载数据
        if not self.load_data():
            return False
        
        # 2. 创建目录
        if not self.setup_directories():
            return False
        
        # 3. 复制HTML文件
        copied_files = self.copy_html_files()
        if not copied_files:
            print("没有成功复制任何文件")
            return False
        
        # 4. 生成索引页面
        main_html_path = self.generate_index_html(copied_files)
        
        # 5. 输出访问URL
        access_url = f"http://{self.server_ip}:{self.server_port}/files/{self.timestamp}/{self.page_name}.html"
        
        print(f"\n✅ HTML整合完成!")
        print(f"📁 输出目录: {self.timestamped_dir}")
        print(f"📄 主页面: {main_html_path}")
        print(f"📂 HTML文件目录: {self.html_subdir}")
        print(f"📊 成功处理 {len(copied_files)} 个文件")
        print(f"\n🌐 网页访问地址:")
        print(f"   {access_url}")
        
        return True

def main():
    parser = argparse.ArgumentParser(description='HTML整合工具')
    parser.add_argument('-s', '--source', required=True, help='输入CSV文件路径')
    parser.add_argument('-o', '--output', required=True, help='输出目录路径')
    parser.add_argument('-p', '--page', required=True, help='主HTML页面名称')
    parser.add_argument('--ip', default='114.55.147.235', help='服务器IP地址')
    parser.add_argument('--port', default='80', help='服务器端口')
    
    args = parser.parse_args()
    
    integrator = HTMLIntegrator(args.source, args.output, args.page, args.ip, args.port)
    success = integrator.integrate()
    
    if success:
        print("\n🎉 HTML整合工具执行成功!")
    else:
        print("\n❌ HTML整合工具执行失败!")
        exit(1)

if __name__ == '__main__':
    main()